using System;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mail;
using System.Web.UI;
using System.Xml;
using log4net;

/*	-----------------------------------------------------------------------	
	Copyright:	umlungu consulting (pty) ltd
	Author:		Alan Benington
	Started:	2008-06-14
	Status:		release	
	Version:	2.0.0
	Build:		20080614
	License:	GNU General Public License
	-----------------------------------------------------------------------	*/

/*	-----------------------------------------------------------------------	
	Development Notes:
	==================
	20080614:	Initial release.
	---------------------------------------------------------------------------	*/

namespace umlungu.engineX.blogX.WebsiteX {
	/// <summary>Description of the enumeration</summary>
	public enum WebsiteXBlogsType {
		/// <summary>view</summary>
	    view = 0,
		/// <summary>add comment</summary>
	    comment = 1,
		/// <summary>approve type</summary>
	    approve = 2,
		/// <summary>delete type</summary>
	    delete = 3
	}

	/// <summary>
	/// Description of the WebsiteXBlogs class.
	/// <para>Additional information about the class</para>
	/// </summary>
	public class WebsiteXBlogs : x_broker {
		#region Invisible properties
		public static readonly ILog Logger = LogManager.GetLogger(typeof(WebsiteXBlogs));
        //public static readonly ILog Logger = LogManager.GetLogger(typeof(WebsiteXMailngList));
        private const bool approve_immediate = false;
		#endregion

		#region Constant fake author strings
		private const string LINK_APPROVE_AWAITING = "talkspace_comment_approve";
		private const string LINK_APPROVE_IMMEDIATE = "talkspace_blog";
        private const string BLOG_EMAIL = "WebsiteX@umlungu.com";
		private const string BLOG_SUBJECT = "Support blog comment approval";
		
		private string spam_words = "http|[url|mailto|fuck|cunt|penis|pussy|arsehole|vagina|tits";
		private const string author_fake = "ED";
		private const string author_fake_display = "[Ed Imposter]";
		private const string author_real = "0824908889";
		private const string author_real_display = "Ed";
		#endregion

		#region Constant error strings
		private const string error_no_error		= "Not an error";
		private const string error_service		= "WebsiteXBlogs error::";
		private const string error_service_view	= " View error";
		private const string error_service_type	= " No such service type";
		private const string error_service_send = "Approval email sending error: ";
		private const string error_comment_approve = "Comment approval error: ";
		private const string error_comment_delete = "Comment delete error: ";
		#endregion

		#region Visible properties
		private WebsiteXBlogsType serviceType;
		/// <summary>Definiton of the property</summary>
		/// <value>Description of the value of the property</value>
		public WebsiteXBlogsType ServiceType {
			get { return serviceType; }
			set { serviceType = value; }
		}
		#endregion

		#region Constructors/Destructors
		/// <overloads>Constructor</overloads>
		/// <summary>Default constructor</summary>
		/// <param name="thispage">The web application Page object</param>
        public WebsiteXBlogs(displayX thispage): base(thispage){
			log4net.Config.XmlConfigurator.Configure();
		}
		#endregion

		#region Public methods
		public override void Process(string type) {
	
            getType(type);
            switch (serviceType) {
				case WebsiteXBlogsType.view:	view();			break;
				case WebsiteXBlogsType.comment:	comment();		break;
				case WebsiteXBlogsType.approve:	approve();		break;
				case WebsiteXBlogsType.delete:	delete();		break;
			}
		}
		#endregion
		
		#region Protected methods
		#endregion
				
		#region Private methods
		/// <summary>Gets the type of service</summary>
		private void getType(string thistype) {
            switch (thistype) {

				case "view":		serviceType = WebsiteXBlogsType.view;		break;
				case "comment":		serviceType = WebsiteXBlogsType.comment;		break;
				case "approve":		serviceType = WebsiteXBlogsType.approve;		break;
				case "delete":		serviceType = WebsiteXBlogsType.delete;		break;
				default:			throw(new x_exception("error_service_type", String.Concat(error_service, error_service_type)));

			}
		}
		/// <summary></summary>
		private void view() {
			UIPage.UserProfile.Add("Comment_Blog", UIPage.Parameters.Blog);
			UIPage.UserProfile.Add("Comment_Topic", UIPage.Parameters.Topic);
            UIPage.UserProfile.Add("Comment_Space", UIPage.Parameters.Spaces);
			clear();
		}
		/// <summary></summary>
		private void comment() {
           
			// test for spam by checking for blog and topic
			string _blogid = _GetRequest(true, "Comment_Blog", "");
			string _blogtopic = _GetRequest(true, "Comment_Topic", "");
            string _blogname = _GetRequest(true, "Comment_Space", "");
            string _commentauthor = fakeEd(_GetRequest(true, "Comment_Name", ""), true);
			string _commenttitle = _GetRequest(true, "Comment_Title", "");
			string _commenttext = _GetRequest(true, "Comment", "");
			if (_blogid != "" && _blogtopic != "" && _commentauthor != "" && _commenttitle != "" && _commenttext != "") {
				
                
                Logger.Debug(String.Concat(_blogname, _blogtopic, _blogid, "public", _commentauthor, _commenttitle, _commenttext));
                if (!SpamCheck(_commenttitle, 256, 30, false) && !SpamCheck(_commenttext, 4092, 30, false)) {
					if (!SpamCheck(spam_words, _commenttitle, false) && !SpamCheck(spam_words, _commenttext, false)) {
						x_blog blogx = new x_blog(UIPage.Application);
						blogx.AddComment(_blogname, _blogtopic, System.Convert.ToInt32(_blogid), "public", _commentauthor, _commenttitle, _commenttext, approve_immediate);
						approvalEmail(blogx.Blog, _blogname, _blogtopic, blogx.CommentID);
						if (!approve_immediate)
							throw(new x_exception(LINK_APPROVE_AWAITING, "Awaiting approval"));
					}
				}
				// ensure that the comment response contains this topic/blog
				UIPage.Parameters.Topic = _blogtopic;
				UIPage.Parameters.Blog = _blogid;
				UIPage.Parameters.Blogs = _blogid;
			}
			clear();
		}
		/// <summary></summary>
		private void approve() {
			string blogname = _GetRequest(false, "name", "");
			string blogtopic = _GetRequest(false, "topic", "");
			string blogid = _GetRequest(false, "id", "");
			string blogcid = _GetRequest(false, "cid", "");
			try {
				x_blog blogx = new x_blog(UIPage.Application);
				blogx.ApproveComment(blogname, blogtopic, blogid, blogcid);
				
				// ensure that the comment response contains this topic/blog
				UIPage.Parameters.Spaces = blogname;
				UIPage.Parameters.Topic = blogtopic;
				UIPage.Parameters.Blog = blogid;
				UIPage.Parameters.Blogs = blogid;
			} 
			catch(System.Exception e) {
				throw(new x_exception("error_comment_approve", String.Concat(error_service, error_comment_approve, e.Message)));
			}
		}
		/// <summary></summary>
		private void delete() {
			string blogname = _GetRequest(false, "name", "");
			string blogtopic = _GetRequest(false, "topic", "");
			string blogid = _GetRequest(false, "id", "");
			string blogcid = _GetRequest(false, "cid", "");
			try {
				x_blog blogx = new x_blog(UIPage.Application);
				blogx.DeleteComment(blogname, blogtopic, blogid, blogcid);
				
				// ensure that the comment response contains this topic/blog
				UIPage.Parameters.Spaces = blogname;
				UIPage.Parameters.Topic = blogtopic;
				UIPage.Parameters.Blog = blogid;
				UIPage.Parameters.Blogs = blogid;
			} 
			catch(System.Exception e) {
				throw(new x_exception("error_comment_delete", String.Concat(error_service, error_comment_delete, e.Message)));
			}
		}
		private void clear() {
			UIPage.UserProfile.Add("Comment_Title", "");
			UIPage.UserProfile.Add("Comment", "");
		}
		private string fakeEd(string author) {
			if (author.ToUpper() == author_fake)
				return author_fake_display;
			else if (author == author_real)
				return author_real_display;
			else
				return author;
		}
		private string fakeEd(string author, bool wantRegular) {
			if (!wantRegular)
				return fakeEd(author);
			else if (author == author_real)
				return author_real_display;
			else {
				string pat = @"(Ed\sHall)|(Ed)";
				Regex r = new Regex(pat, RegexOptions.IgnoreCase);
				Match m = r.Match(author);
				return (m.Success)? author_fake_display : author;
			}
		}
		private void approvalEmail(XmlElement blog, string space, string topic, string comment) {
           
            try {
				XmlDocument blogdoc = new XmlDocument();
				blogdoc.LoadXml("<blogs/>");
				XmlElement blogel = blogdoc.DocumentElement.AppendChild(blogdoc.ImportNode(blog, true)) as XmlElement;
				blogel.SetAttribute("space", space);
				blogel.SetAttribute("topic", topic);
				blogel.SetAttribute("comment", comment);

                umlungu.engineX.emailX.x_email thisemail = new umlungu.engineX.emailX.x_email();
				thisemail.Bcc = "chris@umlungu.com";
				thisemail.Subject = BLOG_SUBJECT;
				thisemail.To = BLOG_EMAIL;
                thisemail.Type = umlungu.engineX.emailX.x_emailtype.html;
				thisemail.Send (blogdoc, _GetTemplate("WebsiteXBlog.xsl"));
			}
			catch(System.Exception e) {
				throw(new x_exception("error_service_send", String.Concat(error_service, error_service_send, e.Message)));
			}
		}
		#endregion
	}
}
